<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="姓名" prop="expertName">
        <el-input v-model="formData.expertName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="专家单位" prop="expertUnit">
        <el-input v-model="formData.expertUnit" placeholder="请输入专家单位" />
      </el-form-item>
      <el-form-item label="电话" prop="expertPhone">
        <el-input v-model="formData.expertPhone" placeholder="请输入电话" />
      </el-form-item>
      <el-form-item label="所属专家库" prop="expertMajor">
        <el-select v-model="formData.expertMajor">
          <el-option
              v-for="item in majorList"
              :key="item.dataName"
              :label="item.dataName"
              :value="item.dataName"/>
          </el-select>
      </el-form-item>
      <el-form-item label="专业" prop="major">
        <el-input v-model="formData.major" placeholder="请输入职称" />
      </el-form-item>
      <el-form-item label="职称" prop="expertTitle">
        <el-input v-model="formData.expertTitle" placeholder="请输入职称" />
      </el-form-item>
      <el-form-item label="身份代码" prop="expertIden">
        <el-input v-model="formData.expertIden" placeholder="请输入身份代码" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber">
        <el-input v-model="formData.idNumber" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InfoApi, InfoVO } from '@/api/expert/expertinfo'

import {BasedataApi,BasedataVO} from '@/api/expert/expertbasedata'

/** 专家信息 表单 */
defineOptions({ name: 'InfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const majorList = ref<BasedataVO[]>([])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  expertName: undefined,
  expertUnit: undefined,
  expertPhone: undefined,
  expertMajor: undefined,
  expertTitle: undefined,
  expertIden: undefined,
  idNumber:undefined,
  remark: undefined,
  major: undefined
})


// 身份证号校验函数
const validateIdNumber = (rule: any, value: string, callback: any) => {
  if (!value) {
    return callback(new Error(t('validation.required')))
  }
  
  // 身份证号正则表达式
  const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  
  if (!idCardReg.test(value)) {
    return callback(new Error(t('请输入正确身份证号')))
  }
  
  // 18位身份证的验证
  if (value.length === 18) {
    const idCardArray = value.split('')
    // 身份证号码验证因子
    const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    // 身份证号码校验码
    const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
    let sum = 0
    
    for (let i = 0; i < 17; i++) {
      sum += parseInt(idCardArray[i]) * factor[i]
    }
    
    const lastChar = idCardArray[17].toUpperCase()
    if (parity[sum % 11] !== lastChar) {
      return callback(new Error(t('请输入正确身份证号')))
    }
  }
  
  callback()
}
const formRules = reactive({
  expertName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  expertUnit: [{ required: true, message: '专家单位不能为空', trigger: 'blur' }],
  idNumber: [
    { required: true, message: '身份证号不能为空', trigger: 'blur' },
    { validator: validateIdNumber, trigger: 'blur' }
  ],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  getMajorList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await InfoApi.getInfo(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as InfoVO
    if (formType.value === 'create') {
      await InfoApi.createInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await InfoApi.updateInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const getMajorList =async ()=>{
  majorList.value = await BasedataApi.getMajorList()
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    expertName: undefined,
    expertUnit: undefined,
    expertPhone: undefined,
    expertMajor: undefined,
    expertTitle: undefined,
    expertIden: undefined,
    idNumber:undefined,
    major: undefined,
    remark: undefined,
  }
  formRef.value?.resetFields()
}
</script>